/**
 * Created by imouze on 2017-10-17.
 *
 * 数据远程调用通用类
 */

const rawRequest = require('request');

class Remote {
    
    constructor(options) {
        
        this.options = options = options || {};
        options.token = options.token || null;
        options.url = options.url || 'http://172.16.53.53:8080';
    }
    
    baseParams(params) {
        
        params = Object.assign({}, params || {});
        if(this.options.token) {
            params.accesstoken = this.options.token;
        }
        
        return params;
        
    }
    
    addHeaders(headers) {
        this.headers = Object.assign({}, headers || {});
    }
    
    /**
     * 请求远程服务
     * @param method
     * @param path
     * @param params
     * @param callback
     * @returns {Promise}
     */
    request(method, path, params, callback) {
        return new Promise((_resolve, _reject) => {
            
            const resolve = ret => {
                _resolve(ret);
                callback && callback(ret);
            };
            
            const reject = err => {
                _reject(err);
                callback && callback(err);
            };
            
            let headers = {
                "Content-Type": "application/json"
            };
            
            headers = Object.assign(headers, this.headers || {});
            
            let opts = {
                method: method.toUpperCase(),
                url: this.options.url + path,
                headers: headers,
                json: true
            };
            
            if(opts.method === 'GET' || opts.method === 'HEAD') {
                opts.qs = this.baseParams(params);
            } else {
                opts.body = this.baseParams(params);
            }
            
            rawRequest(opts, (err, res, body) => {
                
                if(err) return reject(err);
                // 只要body有值并且包含returncode属性就是成功，否则得到的为错误信息
                if(body && body.hasOwnProperty('returncode')) {
                    resolve(body);
                } else {
                    // 语法错误，状态码错误都走这里
                    reject(new Error(body.message));
                }
                
            });
            
        });
    }
}

module.exports = Remote;
